package com.taldh.springframework.beanlifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MysqlConfigAdapter implements BeanPostProcessor, ApplicationContextAware {

    @Autowired
    private ApplicationContext applicationContext;

    @Value("mysql.username")
    private String username;

    @Value("mysql.password")
    private String password;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//        if (bean instanceof XxxDatabase) {
//            ((XxxDatabase)bean).setUsername(username);
//            ((XxxDatabase)bean).setPassword(password);
//        }
        if( applicationContext.getParentBeanFactory() instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) applicationContext.getParentBeanFactory()).addBeanPostProcessor(this);
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
